using System;
using System.Windows.Forms;
using CastleSample.Business.Client;
using CastleSample.Business.Interface;
using CastleSample.Entity;

namespace CastleSample.MembershipModule
{
    public partial class FormUserLogin : Form
    {
        public FormUserLogin()
        {
            InitializeComponent();
        }

        private void buttonLogin_Click(object sender, EventArgs e)
        {
            if (UserContext.Current.LoggedIn)
            {
                IMembershipBizService membershipService1 = UserContext.Current.OnlineMode ? BizServiceFactory.GetRemoteService<IMembershipBizService>() : BizServiceFactory.GetLocalService<IMembershipBizService>();
                UserContext.Current = membershipService1.UserLogout(UserContext.Current);
            }

            IMembershipBizService membershipService = checkBoxOnlineMode.Checked ? BizServiceFactory.GetRemoteService<IMembershipBizService>() : BizServiceFactory.GetLocalService<IMembershipBizService>();

            UserContext context;
            try
            {
                context = membershipService.UserLogin(textBoxUserName.Text, textBoxPassword.Text);
            }
            catch (ArgumentNullException ex)
            {
                if (ex.ParamName != "userName")
                {
                    throw;
                }
                MessageBox.Show(this, "Please input user name.");
                return;
            }
            if (context != null)
            {
                UserContext.Current = context;
                Close();
            }
            else
            {
                MessageBox.Show(this, "User name or password not correct, please try again!");
                textBoxPassword.Text = "";
                textBoxUserName.SelectAll();
                textBoxUserName.Focus();
            }
        }

        private void buttonCancel_Click(object sender, EventArgs e)
        {
            Close();
        }
    }
}